package main;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class Parser {
	List<String> operators;
	HashMap<String, String> rawTasks = new HashMap<String, String>();
	private Graph graph = new Graph();
	private String filename;
	
	public Parser(String filename) {
		this.filename = filename;
	}
	
	public Graph parse() {
		assert filename != null;
		return parse(filename);
	}
	
		
	public Graph parse(String filename) {
		List<String> lines = null;
		
		try {
			lines = Files.readAllLines(Paths.get(filename), Charset.defaultCharset());
		} catch (IOException e) {
			e.printStackTrace();
		}
		Iterator<String> iterator = lines.iterator();
		Task task;
		while(iterator.hasNext()) {
			//System.out.println(i.next());
			String thisLine = iterator.next();
			String[] tokens = thisLine.split(" ");
			if (graph.formsCycle(tokens[0])) {
				System.out.println("Input graph has cycle(s)!");
				System.exit(-1);
			}
			task = new Task(tokens[0], tokens[1] + " " + tokens[2]);
			for (int i = 3; i < tokens.length; i++) {
				Task tempTask = graph.getTaskById(tokens[i]);
				task.addPredecessor(tempTask);
			}
			graph.addTask(task);
		}
		
		return graph;
	}
	
}
